package com.hyj.serve.manage.configure.sql;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author HeYuJie
 * @date 2022/6/2
 */
@Component
public class DataBaseConfig {

    @Bean
    public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) throws SQLException {
        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
        dataSourceInitializer.setDataSource(dataSource);

        HikariDataSource hikariDataSource = (HikariDataSource) dataSource;
        String jdbcUrl = hikariDataSource.getJdbcUrl();
        int i = jdbcUrl.lastIndexOf(':');
        String dbFile = jdbcUrl.substring(i+1);
        File file = new File(dbFile);
        if(!file.exists()){
            ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
            resourceDatabasePopulator.addScript(new ClassPathResource("data/schema.sql"));
            dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
        }
        return dataSourceInitializer;
    }
}
